/**
 * 
 */
package com.cchr.acms.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cchr.acms.constant.CaseStatus;
import com.cchr.acms.model.AbusedPerson;
import com.cchr.acms.model.Attorney;
import com.cchr.acms.model.CaseAudit;
import com.cchr.acms.model.CaseFollowUp;
import com.cchr.acms.model.CaseInfo;
import com.cchr.acms.model.DoctorInfo;
import com.cchr.acms.model.FacilityInfo;
import com.cchr.acms.model.ReportingPerson;
import com.cchr.acms.service.AbuseTypeService;
import com.cchr.acms.service.AbusedPersonService;
import com.cchr.acms.service.ActionService;
import com.cchr.acms.service.AttorneyService;
import com.cchr.acms.service.CaseAuditService;
import com.cchr.acms.service.CaseFollowUpService;
import com.cchr.acms.service.CaseInfoService;
import com.cchr.acms.service.CaseService;
import com.cchr.acms.service.DoctorInfoService;
import com.cchr.acms.service.DrugService;
import com.cchr.acms.service.FacilityInfoService;
import com.cchr.acms.service.ReportingPersonService;
import com.cchr.acms.util.ChangeHistoryDisplayData;
import com.cchr.acms.util.ChangeResult;
import com.cchr.acms.util.DataUtil;
import com.cchr.acms.util.ListUtil;

import net.sf.json.JSONObject;

//import net.sf.json.JSONObject;

/**
 * @author Administrator
 *
 */
@Service
public class CaseServiceImpl implements CaseService {
	@Autowired
	private CaseInfoService caseInfoService;
	@Autowired
	private AbusedPersonService abusedPersonService;
	@Autowired
	private ReportingPersonService reportingPersonService;
	@Autowired
	private DrugService drugService;
	@Autowired
	private AbuseTypeService abuseTypeService;
	@Autowired
	private FacilityInfoService FacilityInfoService;
	@Autowired
	private DoctorInfoService doctorInfoService;
	@Autowired
	private AttorneyService attorneyService;
	@Autowired
	private ActionService actionService;
	@Autowired
	private CaseFollowUpService caseFollowUpService;
	@Autowired
	private CaseAuditService caseAuditService;
	
	private static final Logger operateLogger = LoggerFactory.getLogger("operateLog");

	public void addCase(CaseInfo caseInfo,String[] drugIds,String[] actionsCheckbox,String[] abusetypeCheckbox,String[] insuranceTypeCheckbox,String currUser)  throws Exception {
		Date now = new Date();
		caseInfo.setStatus(CaseStatus.NEW.getValue());
		caseInfo.setCreatedBy(currUser);
		caseInfo.setLastUpdateDate(now);
		caseInfo.setLastUpdatedBy(currUser);
		caseInfo.setCreateDate(now);
		
		caseInfo.setTypeIds(ListUtil.ArrayToString(abusetypeCheckbox, ","));
		caseInfo.setDrugIds(ListUtil.ArrayToString(drugIds, ","));
		caseInfo.setActionIds(ListUtil.ArrayToString(actionsCheckbox, ","));
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmssSSS");
		String caseNo = "C" + sdf.format(new Date());
		caseInfo.setCaseNo(caseNo);
		
		if(insuranceTypeCheckbox!=null && insuranceTypeCheckbox.length>0){
			StringBuilder insuranceType = new StringBuilder();
			for (String type : insuranceTypeCheckbox) {
				insuranceType.append(type).append(",");
			}
			caseInfo.setInsuranceType(insuranceType.toString());
		}
		
		JSONObject caseObject=JSONObject.fromObject(caseInfo);
		operateLogger.info("[case/create-insertCaseInfo]--Start--[caseInfo:"+caseObject.toString()+"]");
		
		caseInfoService.insertCaseInfo(caseInfo);
		int caseId = caseInfo.getId();
		//先生成caseid
		AbusedPerson abusedPerson = caseInfo.getAbusedPerson();
		abusedPerson.setCaseId(caseId);
		
		JSONObject personObject=JSONObject.fromObject(abusedPerson);
        operateLogger.info("[case/create-insertAbusedPerson]--Start--[abusedPerson:"+personObject.toString()+"]");
        
		abusedPersonService.insertAbusedPerson(abusedPerson);
		ReportingPerson reportingPerson = caseInfo.getReportedBy();
		reportingPerson.setCaseId(caseId);
		
		JSONObject reportObject=JSONObject.fromObject(reportingPerson);
        operateLogger.info("[case/create-insertReportingPerson]--Start--[reportingPerson:"+reportObject.toString()+"]");
        
		reportingPersonService.insertReportingPerson(reportingPerson);
	 
		int fsize=0; 
		if(caseInfo.getFacilityInfos()!=null&&(fsize = caseInfo.getFacilityInfos().size())>0){
			for (int i = 0; i < fsize; i++) {
				FacilityInfo info = caseInfo.getFacilityInfos().get(i);
				info.setCaseId(caseId);
				FacilityInfoService.insertFacilityInfo(info);
			}
		}
		int dsize = 0;
		if(caseInfo.getDoctorInfos()!=null&&(dsize = caseInfo.getDoctorInfos().size())>0){
			for (int i = 0; i < dsize; i++) {
				DoctorInfo info = caseInfo.getDoctorInfos().get(i);
				info.setCaseId(caseId);
				doctorInfoService.insertDoctorInfo(info);
			}
			
		}

		Attorney attorney = caseInfo.getAttorney();
		attorney.setCaseId(caseId);
		
		JSONObject attorneyObject=JSONObject.fromObject(attorney);
        operateLogger.info("[case/create-insertAttorney]--Start--[attorney:"+attorneyObject.toString()+"]");
		attorneyService.insertAttorney(attorney);
	}
	
	@Override
	public void updateCase(CaseInfo caseInfo, String[] drugIds, String[] actionsCheckbox, String[] abusetypeCheckbox, String[] insuranceTypeCheckbox, String currUser, Integer id) throws Exception {
		String flagNew = null;
		String flagOld = null;
		ChangeHistoryDisplayData displayData = new ChangeHistoryDisplayData();
		 
		CaseInfo oldCase = caseInfoService.getCaseInfoById(id);
		CaseInfo  newCase = caseInfoService.getCaseInfoById(id);
		
		Date now = new Date();
		
		newCase.setLastUpdateDate(now);
		newCase.setLastUpdatedBy(currUser);
		newCase.setTypeIds(ListUtil.ArrayToString(abusetypeCheckbox, ","));
		newCase.setDrugIds(ListUtil.ArrayToString(drugIds, ","));
		newCase.setActionIds(ListUtil.ArrayToString(actionsCheckbox, ","));
		newCase.setInsuranceType(ListUtil.ArrayToString(insuranceTypeCheckbox, ","));
		
		// 更新界面信息
		newCase.setCaseStart(caseInfo.getCaseStart());
		newCase.setCaseEnd(caseInfo.getCaseEnd());
		newCase.setSummary(caseInfo.getSummary());
		newCase.setOtherAction(caseInfo.getOtherAction());
		newCase.setSequence(caseInfo.getSequence());
		newCase.setDrugsPrescribed(caseInfo.getDrugsPrescribed());
		newCase.setBestTimeToContact(caseInfo.getBestTimeToContact());
		newCase.setBestWayToContact(caseInfo.getBestWayToContact());
		newCase.setDifferentAbusedPerson(caseInfo.getDifferentAbusedPerson());
		newCase.setStillTakeDrugs(caseInfo.getStillTakeDrugs());
		newCase.setDrugsTakeTime(caseInfo.getDrugsTakeTime());
		newCase.setDrugsDosage(caseInfo.getDrugsDosage());
		caseInfoService.updateCaseInfo(newCase);
		int caseId = id;
		//先生成caseid
		AbusedPerson oldAbusePerson = abusedPersonService.getAbusedPersonByCaseId(caseId);
		
		abusedPersonService.deleteAbusedPersonByCaseId(caseId);
		AbusedPerson abusedPerson = caseInfo.getAbusedPerson();
		abusedPerson.setCaseId(caseId);
		abusedPersonService.insertAbusedPerson(abusedPerson);
		
		ReportingPerson oldReportingPerson = reportingPersonService.getReportingPersonByCaseId(caseId);
		reportingPersonService.deleteReportingPersonByCaseId(caseId);
		ReportingPerson reportingPerson = caseInfo.getReportedBy();
		reportingPerson.setCaseId(caseId);
		reportingPersonService.insertReportingPerson(reportingPerson);
	 
		int fsize=0; 
		List<FacilityInfo> oldFacilityInfo = FacilityInfoService.getFacilityInfoByCaseId(caseId);
		List<FacilityInfo> newFacilityInfo = new ArrayList<FacilityInfo>();
		
		FacilityInfoService.deleteFacilityInfoByCaseId(caseId);
		if(caseInfo.getFacilityInfos()!=null&&(fsize = caseInfo.getFacilityInfos().size())>0){
			for (int i = 0; i < fsize; i++) {
				FacilityInfo info = caseInfo.getFacilityInfos().get(i);
				info.setCaseId(caseId);
				newFacilityInfo.add(info);
				FacilityInfoService.insertFacilityInfo(info);
			}
		}
		
		int dsize = 0;
		List<DoctorInfo> oldDoctorInfo = doctorInfoService.queryDoctorInfoByCaseId(caseId);
		List<DoctorInfo> newDoctorInfo = new ArrayList<DoctorInfo>();
		
		doctorInfoService.deleteDoctorInfoByCaseId(caseId);
		if(caseInfo.getDoctorInfos()!=null&&(dsize = caseInfo.getDoctorInfos().size())>0){
			for (int i = 0; i < dsize; i++) {
				DoctorInfo info = caseInfo.getDoctorInfos().get(i);
				info.setCaseId(caseId);
				newDoctorInfo.add(info);
				doctorInfoService.insertDoctorInfo(info);
			}
			
		}

		Attorney oldAttorney = attorneyService.getAttorneyByCaseId(caseId);
		attorneyService.deleteAttorneyByCaseId(caseId);
		Attorney newAttorney = caseInfo.getAttorney();
		newAttorney.setCaseId(caseId);
		attorneyService.insertAttorney(newAttorney);
	    
		
		//auditor for abuse case person's info
		// check for caseInfo
		List<String> needComparedFields2 = new ArrayList<String>();

		needComparedFields2.add("caseStart");
		needComparedFields2.add("caseEnd");
		needComparedFields2.add("summary");  
		needComparedFields2.add("typeIds");
		needComparedFields2.add("actionIds");
		needComparedFields2.add("drugIds");
		needComparedFields2.add("otherAction");
		needComparedFields2.add("drugsPrescribed");
		needComparedFields2.add("bestTimeToContact");
		needComparedFields2.add("bestWayToContact");
		needComparedFields2.add("differentAbusedPerson");
		needComparedFields2.add("stillTakeDrugs");
		
		List<ChangeResult> changeResults = DataUtil.compareObjectByFields(oldCase, newCase, needComparedFields2);
		
		if(changeResults.size() > 0)
		{
			CaseAudit audit = new CaseAudit();
			audit.setAction("Update");
			audit.setUpdatedTime(new Date());
			audit.setUpdatedBy(currUser);
			audit.setCaseId(id);
			StringBuilder updateContent = new StringBuilder();
			for(ChangeResult changeResult : changeResults)
			{	
				StringBuilder oldAbuseType = new StringBuilder(); 
				StringBuilder newAbuseType = new StringBuilder();
				StringBuilder oldAction = new StringBuilder(); 
				StringBuilder newAction = new StringBuilder();
				StringBuilder oldDrug = new StringBuilder(); 
				StringBuilder newDrug = new StringBuilder();
				
				switch(changeResult.getKey()){
				case "drugsPrescribed" :
				case "differentAbusedPerson" :
				case "stillTakeDrugs" :
					if (changeResult.getOldValue().toString().equals("1"))
						{
						   flagOld = "yes";
						}else{
						   flagOld = "no";
						}
					if (changeResult.getNewValue().toString().equals("1"))
					{
					   flagNew = "yes";
					}else{
						flagNew = "no";
					}
					
					updateContent.append("\"Person\'s Info\" section " ).append("\"").append(displayData.getEasyUnderstandingFiledName(changeResult.getKey())).append("\"").append(" has changed from ")  
					.append("\"").append(flagOld).append("\"").append(" to ").append("\"").append(flagNew).append("\"")
					.append("<br>");
					flagNew="";
					flagOld="";
					break;
				case "typeIds" :
					
					  if (changeResult.getOldValue().toString().length()>0) {
				      String[] arrayStr =new String[]{};
				      arrayStr = changeResult.getOldValue().toString().split(",");
				      List<String> list = java.util.Arrays.asList(arrayStr);
					
					      for(String s:list){
							  oldAbuseType.append(abuseTypeService.getAbuseTypeName(Integer.parseInt(s))).append(",");
						  }
					  }else{
						  oldAbuseType.append("").append(",");
					  }
					  
					  if (changeResult.getNewValue().toString().length()>0) {
					  String[] arrayStr1 =new String[]{};
				      arrayStr1 = changeResult.getNewValue().toString().split(",");
				      List<String> list2 = java.util.Arrays.asList(arrayStr1);
					  
				      for(String s1:list2){
						  newAbuseType.append(abuseTypeService.getAbuseTypeName(Integer.parseInt(s1))).append(",");
					  }
				      }else{
				    	  newAbuseType.append("").append(",");
				      }
					  oldAbuseType.deleteCharAt(oldAbuseType.length()-1);
					  newAbuseType.deleteCharAt(newAbuseType.length()-1);
					  
					updateContent.append("\"Person\'s Info\" section " ).append("\"").append(displayData.getEasyUnderstandingFiledName(changeResult.getKey())).append("\"").append(" has changed from ")  
					.append("\"").append(oldAbuseType.toString()).append("\"").append(" to ").append("\"").append(newAbuseType.toString()).append("\"")
					.append("<br>");
					break;
				case "actionIds":
					if (changeResult.getOldValue().toString().length()>0){
						 String[] arrayStr3 =new String[]{};
					      arrayStr3 = changeResult.getOldValue().toString().split(",");
					      List<String> list3 = java.util.Arrays.asList(arrayStr3);
						
						      for(String s3:list3){
								  oldAction.append(actionService.getActionById(Integer.parseInt(s3)).getName()).append(",");
							  }
						}else{
							  oldAction.append("").append(",");
						  }
						  
					if (changeResult.getNewValue().toString().length()>0){
						 String[] arrayStr4 =new String[]{};
					      arrayStr4 = changeResult.getNewValue().toString().split(",");
					      List<String> list4 = java.util.Arrays.asList(arrayStr4);
						
						      for(String s4:list4){
						    	  newAction.append(actionService.getActionById(Integer.parseInt(s4)).getName()).append(",");
							  }
						}else{
							  newAction.append("").append(",");
						  }
					oldAction.deleteCharAt(oldAction.length()-1);
					newAction.deleteCharAt(newAction.length()-1);
					updateContent.append("\"Person\'s Info\" section " ).append("\"").append(displayData.getEasyUnderstandingFiledName(changeResult.getKey())).append("\"").append(" has changed from ")  
					.append("\"").append(oldAction.toString()).append("\"").append(" to ").append("\"").append(newAction.toString()).append("\"")
					.append("<br>");
					break;
				case "otherAction":
					updateContent.append("\"Person\'s Info\" section " ).append("\"").append(displayData.getEasyUnderstandingFiledName(changeResult.getKey())).append("\"").append(" has changed from ")  
					.append("\"").append(changeResult.getOldValue()).append("\"").append(" to ").append("\"").append(changeResult.getNewValue()).append("\"")
					.append("<br>");
					
				break;
				case "drugIds":
					if (changeResult.getOldValue().toString().length()>0){
						 String[] arrayStr5 =new String[]{};
					      arrayStr5 = changeResult.getOldValue().toString().split(",");
					      List<String> list5 = java.util.Arrays.asList(arrayStr5);
						
						      for(String s5:list5){
								  oldDrug.append(drugService.getDrugById(Integer.parseInt(s5)).getName()).append(",");
							  }
						}else{
							  oldDrug.append("").append(",");
						  }
						  
					if (changeResult.getNewValue().toString().length()>0){
						 String[] arrayStr6 =new String[]{};
					      arrayStr6 = changeResult.getNewValue().toString().split(",");
					      List<String> list6 = java.util.Arrays.asList(arrayStr6);
						
						      for(String s6:list6){
						    	  newDrug.append(drugService.getDrugById(Integer.parseInt(s6)).getName()).append(",");
							  }
						}else{
							  newDrug.append("").append(",");
						  }
					oldDrug.deleteCharAt(oldDrug.length()-1);
					newDrug.deleteCharAt(newDrug.length()-1);
					updateContent.append("\"Person\'s Info\" section " ).append("\"").append(displayData.getEasyUnderstandingFiledName(changeResult.getKey())).append("\"").append(" has changed from ")  
					.append("\"").append(oldDrug.toString()).append("\"").append(" to ").append("\"").append(newDrug.toString()).append("\"")
					.append("<br>");
					break;
					
				default: 
					
					updateContent.append("\"Person\'s Info\" section " ).append("\"").append(displayData.getEasyUnderstandingFiledName(changeResult.getKey())).append("\"").append(" has changed from ")  
					.append("\"").append(changeResult.getOldValue()).append("\"").append(" to ").append("\"").append(changeResult.getNewValue()).append("\"")
					.append("<br>");

				}
				
			}
			audit.setUpdatedAfter(updateContent.toString());
			
			caseAuditService.insertCaseAudit(audit); //for person info section
			}
		
		//auditor for abused person
				List<String> needComparedFields3 = new ArrayList<String>();

				needComparedFields3.add("firstName");
				needComparedFields3.add("middleName");
				needComparedFields3.add("lastName");  
				needComparedFields3.add("email");
				needComparedFields3.add("city");
				needComparedFields3.add("state");
				needComparedFields3.add("country");
				needComparedFields3.add("telephone");
				needComparedFields3.add("zip");
				needComparedFields3.add("birthDay");
				needComparedFields3.add("streetAddress");
				needComparedFields3.add("age");
				
				List<ChangeResult> changeResults3 = DataUtil.compareObjectByFields(oldAbusePerson, abusedPerson, needComparedFields3);
				
				if(changeResults3.size() > 0)
				{
					CaseAudit audit2 = new CaseAudit();
					audit2.setAction("Update");
					audit2.setUpdatedTime(new Date());
					audit2.setUpdatedBy(currUser);
					audit2.setCaseId(id);
					StringBuilder updateContent2 = new StringBuilder();
					for(ChangeResult changeResult : changeResults3)
					{	
						
							updateContent2.append("\"Person\'s Info\" section " ).append("\"").append(displayData.getEasyUnderstandingFiledNameForAbusedPerson(changeResult.getKey())).append("\"").append(" has changed from ")  
							.append("\"").append(changeResult.getOldValue()).append("\"").append(" to ").append("\"").append(changeResult.getNewValue()).append("\"")
							.append("<br>");

						
					}
					audit2.setUpdatedAfter(updateContent2.toString());
					caseAuditService.insertCaseAudit(audit2);  //for person info section
					}
				
				//auditor for reporting person
				List<String> needComparedFields4 = new ArrayList<String>();

				needComparedFields4.add("firstName");
				needComparedFields4.add("middleName");
				needComparedFields4.add("lastName");  
				needComparedFields4.add("email");
				needComparedFields4.add("city");
				needComparedFields4.add("state");
				needComparedFields4.add("country");
				needComparedFields4.add("telephone");
				needComparedFields4.add("zip");
				needComparedFields4.add("birthDay");
				needComparedFields4.add("streetAddress");
				needComparedFields4.add("relation");  
				needComparedFields4.add("relationOther"); 	
				
				List<ChangeResult> changeResults4 = DataUtil.compareObjectByFields(oldReportingPerson, reportingPerson, needComparedFields4);
				
				if(changeResults4.size() > 0)
				{
					CaseAudit audit3 = new CaseAudit();
					audit3.setAction("Update");
					audit3.setUpdatedTime(new Date());
					audit3.setUpdatedBy(currUser);
					audit3.setCaseId(id);
					StringBuilder updateContent3 = new StringBuilder();
					for(ChangeResult changeResult : changeResults4)
					{	
							updateContent3.append("\"Person\'s Info\" section " ).append("\"").append(displayData.getEasyUnderstandingFiledNameForReportingPerson(changeResult.getKey())).append("\"").append(" has changed from ")  
							.append("\"").append(changeResult.getOldValue()).append("\"").append(" to ").append("\"").append(changeResult.getNewValue()).append("\"")
							.append("<br>");
					}
					audit3.setUpdatedAfter(updateContent3.toString());
					caseAuditService.insertCaseAudit(audit3); //for person info section
					}
				
				//auditor for facility info
				List<String> needComparedFields5 = new ArrayList<String>();
    
				needComparedFields5.add("name");
				needComparedFields5.add("city");
				needComparedFields5.add("state");  
				needComparedFields5.add("zip");
				needComparedFields5.add("country");
				needComparedFields5.add("streetAddress");
				needComparedFields5.add("telephone");
				needComparedFields5.add("type");
				needComparedFields5.add("typeOther");
				CaseAudit audit4 = new CaseAudit();
				StringBuilder updateContent4 = new StringBuilder();
				for (int i=0;i<oldFacilityInfo.size();i++){
					List<ChangeResult> changeResults5 = DataUtil.compareObjectByFields(oldFacilityInfo.get(i), newFacilityInfo.get(i), needComparedFields5);
					
					if(changeResults5.size() > 0)
					{
					
						audit4.setAction("Update");
						audit4.setUpdatedTime(new Date());
						audit4.setUpdatedBy(currUser);
						audit4.setCaseId(id);
					
						for(ChangeResult changeResult : changeResults5)
						{	
								updateContent4.append("\"Person\'s Info\" section " ).append("\"").append(displayData.getEasyUnderstandingFiledNameForFacility(changeResult.getKey())).append("\"").append(" has changed from ")  
								.append("\"").append(changeResult.getOldValue()).append("\"").append(" to ").append("\"").append(changeResult.getNewValue()).append("\"")
								.append("<br>");
						}
					}
				}
				if(null != updateContent4 && updateContent4.toString().length()>1){
					audit4.setUpdatedAfter(updateContent4.toString());
					caseAuditService.insertCaseAudit(audit4); //for person info section
				}

				
				//auditor for doctor info
				List<String> needComparedFields6 = new ArrayList<String>();
    			
				needComparedFields6.add("name");
				needComparedFields6.add("lastName");
				needComparedFields6.add("docType");  
				needComparedFields6.add("zip");
				needComparedFields6.add("city");
				needComparedFields6.add("state");
				needComparedFields6.add("country");
				needComparedFields6.add("streetAddress");
				needComparedFields6.add("telephone");
				StringBuilder updateContent5 = new StringBuilder();
				CaseAudit audit5 = new CaseAudit();
				for (int i=0;i<oldDoctorInfo.size();i++){
					List<ChangeResult> changeResults6 = DataUtil.compareObjectByFields(oldDoctorInfo.get(i), newDoctorInfo.get(i), needComparedFields6);
					
					if(changeResults6.size() > 0)
					{
						
						audit5.setAction("Update");
						audit5.setUpdatedTime(new Date());
						audit5.setUpdatedBy(currUser);
						audit5.setCaseId(id);
						
						for(ChangeResult changeResult : changeResults6)
						{	
								updateContent5.append("\"Person\'s Info\" section " ).append("\"").append(displayData.getEasyUnderstandingFiledNameForDoctor(changeResult.getKey())).append("\"").append(" has changed from ")  
								.append("\"").append(changeResult.getOldValue()).append("\"").append(" to ").append("\"").append(changeResult.getNewValue()).append("\"")
								.append("<br>");
						}
						}
				}
				if(null != updateContent5 && updateContent5.toString().length()>1){
				audit5.setUpdatedAfter(updateContent5.toString());
				caseAuditService.insertCaseAudit(audit5); //for person info section
				}
					
					//auditor for attorney info
					List<String> needComparedFields7 = new ArrayList<String>();
				  
					needComparedFields7.add("name");
					needComparedFields7.add("city");
					needComparedFields7.add("state");
					needComparedFields7.add("country");
					needComparedFields7.add("telephone");
					needComparedFields7.add("zip");
					needComparedFields7.add("streetAddress");
					needComparedFields7.add("workWithAttorney");
					needComparedFields7.add("assistanceAttorney");  
					needComparedFields7.add("status");
					
					List<ChangeResult> changeResults7 = DataUtil.compareObjectByFields(oldAttorney, newAttorney, needComparedFields7);
					
					if(changeResults7.size() > 0)
					{
						CaseAudit audit7 = new CaseAudit();
						audit7.setAction("Update");
						audit7.setUpdatedTime(new Date());
						audit7.setUpdatedBy(currUser);
						audit7.setCaseId(id);
						StringBuilder updateContent7 = new StringBuilder();
						for(ChangeResult changeResult : changeResults7)
						{	
								
							switch(changeResult.getKey()){
							case "workWithAttorney" :
							case "assistanceAttorney":
								if ((changeResult.getOldValue()!=null)&&("1".equals(changeResult.getOldValue().toString())))
									{
									   flagOld = "yes";
									}else{
									   flagOld = "no";
									}
								if((changeResult.getNewValue()!=null)&&("1".equals(changeResult.getNewValue().toString())))
								{
								   flagNew = "yes";
								}else{
									flagNew = "no";
								}
								
							    updateContent7.append("\"Person\'s Info\" section " ).append("\"").append(displayData.getEasyUnderstandingFiledNameForAttorney(changeResult.getKey())).append("\"").append(" has changed from ")  
								.append("\"").append(flagOld).append("\"").append(" to ").append("\"").append(flagNew).append("\"")
								.append("<br>");
								flagNew="";
								flagOld="";
								break;
								default:
							      updateContent7.append("\"Person\'s Info\" section " ).append("\"").append(displayData.getEasyUnderstandingFiledNameForAttorney(changeResult.getKey())).append("\"").append(" has changed from ")  
								.append("\"").append(changeResult.getOldValue()).append("\"").append(" to ").append("\"").append(changeResult.getNewValue()).append("\"")
								.append("<br>");
							}
						}
						audit7.setUpdatedAfter(updateContent7.toString());
						caseAuditService.insertCaseAudit(audit7);  //for person info section
					}
	}
	
	public void addDetail(CaseFollowUp caseFollowUp, Integer id, String caseStatus, String[] contactWaysCheckbox, String[] insuranceTypeCheckbox, String[] attorneyStatusCheckbox, String currUser) throws Exception{
		String flagNew = null;
		String flagOld = null;
		String byWhoOld = null;
		String byWhoNew = null;
		String acceptFlagOld = null;
		String acceptFlagNew = null;
		ChangeHistoryDisplayData displayData= new ChangeHistoryDisplayData();
		
		//status:new processing,completed
		if(attorneyStatusCheckbox!=null && attorneyStatusCheckbox.length>0){
			StringBuilder attorneyStatus = new StringBuilder();
			for (String status : attorneyStatusCheckbox) {
				attorneyStatus.append(status).append(",");
			}
			caseFollowUp.setAttorneyStatus(attorneyStatus.toString());
		}
		
		if(contactWaysCheckbox!=null && contactWaysCheckbox.length>0){
			StringBuilder contactWays = new StringBuilder();
			for (String contact : contactWaysCheckbox) {
				contactWays.append(contact).append(",");
				
			}
			caseFollowUp.setContactedBy(contactWays.toString());
		}
		
		if(insuranceTypeCheckbox!=null && insuranceTypeCheckbox.length>0){
			StringBuilder contactWays = new StringBuilder();
			for (String contact : insuranceTypeCheckbox) {
				contactWays.append(contact).append(",");
				
			}
			caseFollowUp.setInsuranceType(contactWays.toString());
		}
		
		caseFollowUp.setCaseId(id);
		caseStatus = StringUtils.isEmpty(caseStatus) ? CaseStatus.COMPLETED.getValue() : caseStatus;
		if(caseStatus.equals(CaseStatus.NEW.getValue()) || caseStatus.equals(CaseStatus.ASSIGNED.getValue()))
		{
			caseStatus = CaseStatus.INPROCESS.getValue();
		}
		// 根据类型获取不同的Staff Memeber Name
		if("0".equals(caseFollowUp.getFollowedType()))
		{
			caseFollowUp.setStaffMemeberFirstName(caseFollowUp.getStaffMemeberFirstName1());
			caseFollowUp.setStaffMemeberLastName(caseFollowUp.getStaffMemeberLastName1());
		}
		else
		{
			caseFollowUp.setStaffMemeberFirstName(caseFollowUp.getStaffMemeberFirstName2());
			caseFollowUp.setStaffMemeberLastName(caseFollowUp.getStaffMemeberLastName2());
		}
		CaseInfo caseInfo = caseInfoService.getCaseInfoById(id);
		int result = 1;
		String statusAudit = "";
		if(!caseInfo.getStatus().equals(caseStatus))
		{
		    operateLogger.info("[case/detail-updateCaseStatus]--Start--[id:"+id+"--caseStatus:"+id+"--userName:"+currUser+"]");
		    
			result = caseInfoService.updateCaseStatus(id, caseStatus, currUser);
			
			statusAudit = "\"Follow Up\" section \"Case Status\" has changed from \"" + CaseStatus.getKeyByValue(caseInfo.getStatus()) + "\""+" to "+"\"" + CaseStatus.getKeyByValue(caseStatus)+"\"";
		}
		CaseFollowUp followup = caseFollowUpService.getCaseFollowUpByCaseId(id);
		if(result > 0 && followup == null){
		    JSONObject caseFollowUpObject=JSONObject.fromObject(caseFollowUp);
	        operateLogger.info("[case/detail-insertCaseFollowUp]--Start--[caseFollowUp:"+caseFollowUpObject.toString()+"]");
	        
			caseFollowUpService.insertCaseFollowUp(caseFollowUp);
		}
		else if(result > 0 && followup != null)
		{
			try {
				// audit
				List<String> needComparedFields = new ArrayList<String>();
				needComparedFields.add("beenContacted");
				needComparedFields.add("contactedDate");
				needComparedFields.add("followedType");
				needComparedFields.add("chapter");
				needComparedFields.add("staffMemeberFirstName");
				needComparedFields.add("staffMemeberLastName");
				needComparedFields.add("contactedBy");
				needComparedFields.add("staffMemeberEmail");
				needComparedFields.add("staffMemeberPhoneNumber");
				needComparedFields.add("contactedNotes");  
				needComparedFields.add("insurance1CompanyName");
				needComparedFields.add("insurance2CompanyName");
				needComparedFields.add("notesOnInsuranceDetail");
				needComparedFields.add("attorneyStatus");
				needComparedFields.add("attorneyFirstName");
				needComparedFields.add("attorneyLastName");
				needComparedFields.add("notesOnAttorneyStatus");
				needComparedFields.add("referAttorneyStatus");
				needComparedFields.add("referAttorneyFirstName");
				needComparedFields.add("referAttorneyLastName");
				needComparedFields.add("referAttorneyDate");
				needComparedFields.add("referAttorneyAccteptDate");
				needComparedFields.add("referAttorneyAccteptFlag");
				needComparedFields.add("referAttorneyDeclinedFlag");
				needComparedFields.add("referAttorneyDeclinedDate");
				needComparedFields.add("referAttorneyDeclinedReason");
				needComparedFields.add("notesOnReferal");
				needComparedFields.add("filledWithAgency");
				needComparedFields.add("filleWithAgencyDate");
				needComparedFields.add("filledAgencyName");
				needComparedFields.add("filledAgencyContactName");
				needComparedFields.add("filledAgencyAddress");
				needComparedFields.add("filledAgencyCity");
				needComparedFields.add("filledAgencyState");
				needComparedFields.add("filledAgencyCountry");
				needComparedFields.add("filledAgencyZip");
				needComparedFields.add("compliantResponseReceived");
				needComparedFields.add("compliantResponseContent");
				needComparedFields.add("noteOnCompliant");
				needComparedFields.add("abusedPersonSigneWaiver");
				needComparedFields.add("abusedPersonSigneDate");
				needComparedFields.add("cchrReceivedAbusedDoc");
				needComparedFields.add("cchrReceivedAbusedDocDate");
				needComparedFields.add("otherActionsTaken");
				needComparedFields.add("currentStatusOnCase");
				needComparedFields.add("caseLastUpdatedDate");
				needComparedFields.add("caseCategory");
				List<ChangeResult> changeResults = DataUtil.compareObjectByFields(followup, caseFollowUp, needComparedFields);
				//System.out.println(changeResults.size());
				if(changeResults.size() > 0)
				{
					CaseAudit audit = new CaseAudit();
					audit.setAction("Update");
					audit.setUpdatedTime(new Date());
					audit.setUpdatedBy(currUser);
					audit.setCaseId(id);
					StringBuilder updateContent = new StringBuilder();
					for(ChangeResult changeResult : changeResults)
					{
						
						switch(changeResult.getKey()){
						case "beenContacted" :
						case "userInsurance" :
						case "referAttorneyStatus" :
						case "filledWithAgency" :
						case "compliantResponseReceived" :
						case "abusedPersonSigneWaiver" :
						case "cchrReceivedAbusedDoc" :
							if (null !=changeResult.getOldValue() )
							{
								if ("1".equals(changeResult.getOldValue().toString()))
								{
								   flagOld = "yes";
								}else{
									flagOld = "no";
								}
								
							}else{
								flagOld = "no";
							}
							if ("1".equals(changeResult.getNewValue().toString()))
							{
							   flagNew = "yes";
							}else{
								flagNew = "no";
							}
							
							updateContent.append("\"Follow Up\" section " ).append("\"").append(displayData.getEasyUnderstandingFiledName(changeResult.getKey())).append("\"").append(" has changed from ")  //LEON
							.append("\"").append(flagOld).append("\"").append(" to ").append("\"").append(flagNew).append("\"")
							.append("<br>");
							flagNew="";
							flagOld="";
							break;
						case "followedType" :
							if (null != changeResult.getOldValue()){
								if ("0".equals(changeResult.getOldValue().toString())){
									byWhoOld = "CCHR International";
									
								}else{
									byWhoOld = "CCHR Chapter";}
							}

							if (null != changeResult.getNewValue()){
								if ("0".equals(changeResult.getNewValue().toString())){
									byWhoNew = "CCHR International";
								
								}else{
									byWhoNew = "CCHR Chapter";
								}
							}

							updateContent.append("\"Follow Up\" section " ).append("\"").append(displayData.getEasyUnderstandingFiledName(changeResult.getKey())).append("\"").append(" has changed from ")  //LEON
							.append("\"").append(byWhoOld).append("\"").append(" to ").append("\"").append(byWhoNew).append("\"")
							.append("<br>");
							byWhoOld="";
							byWhoNew="";
							break;
						case "referAttorneyAccteptFlag":
						case "referAttorneyDeclinedFlag":
							if (null == changeResult.getOldValue()){
								acceptFlagOld = "no";
								
							}else{
								acceptFlagOld = "yes";}
							
							if (null == changeResult.getNewValue()){
								acceptFlagNew = "no";
							
							}else{
								acceptFlagNew = "yes";
							}
							updateContent.append("\"Follow Up\" section " ).append("\"").append(displayData.getEasyUnderstandingFiledName(changeResult.getKey())).append("\"").append(" has changed from ")  //LEON
							.append("\"").append(acceptFlagOld).append("\"").append(" to ").append("\"").append(acceptFlagNew).append("\"")
							.append("<br>");
							acceptFlagOld="";
							acceptFlagNew="";
							break;
							
						default: 
							
							updateContent.append("\"Follow Up\" section " ).append("\"").append(displayData.getEasyUnderstandingFiledName(changeResult.getKey())).append("\"").append(" has changed from ")  //LEON
							.append("\"").append(changeResult.getOldValue()).append("\"").append(" to ").append("\"").append(changeResult.getNewValue()).append("\"")
							.append("<br>");

						}
						
					}
					updateContent.append(statusAudit);
					audit.setUpdatedAfter(updateContent.toString());
					
					JSONObject auditObject=JSONObject.fromObject(audit);
		            operateLogger.info("[case/detail-insertCaseAudit]--Start--[audit:"+auditObject.toString()+"]");
		            
					caseAuditService.insertCaseAudit(audit);  //for follow up  section
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			caseFollowUp.setId(followup.getId());
			BeanUtils.copyProperties(caseFollowUp, followup);
			
			JSONObject followupObject=JSONObject.fromObject(followup);
            operateLogger.info("[case/detail-updateCaseFollowUp]--Start--[followup:"+followupObject.toString()+"]");
			caseFollowUpService.updateCaseFollowUp(followup);
		}
	}

}
